const app = getApp()
const ajax = require('../../utils/ajax.js')
// pages/phoneBinding/phoneBinding.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: "",
    code: "",
    checked: 0,
    code_time:0,
    url:""

  },

  phone(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  code(e) {
    this.setData({
      code: e.detail.value
    })
  },

  checkboxChange(e) {
    if (this.data.checked == 0) {
      this.setData({
        checked: 1
      })
    } else {
      this.setData({
        checked: 0
      })
    }
  },

  bind() {
    let that = this
    if (that.data.phone == "") {
      that.toast("手机号码不能为空")
      return false
    } else if (!(/^1[34578]\d{9}$/.test(that.data.phone))) {
      that.toast("请输入正确的手机号码")
      return false;
    } else if (that.data.code==""){
      that.toast("验证码不能为空")
      return false;
    } else if (that.data.checked == 0) {
      that.toast("请仔细阅读相关政策")
      return false;
    }else {
      ajax.wxRequest({
        url: '/index.php/Api/SApi/index/m/register',
        method: 'post',
        data: {
          phone: that.data.phone,
          code: that.data.code,
          vip_id: wx.getStorageSync('vip_id'),
          origin: 'hplgwsc'
        }
      }).then(res => {
        console.log(res)
        if(res.status == 1) {
          wx.setStorageSync('customerid', res.data.customerid)
          wx.showToast({
            title: '绑定成功',
            icon:"success",
            duration:1600
          })
         setTimeout(function(){
           wx.navigateBack()
         },1600)
        } else {
          this.toast('绑定失败，请稍后重试')
        }
      })
    }
  },

  getCode() {
    let that = this
    if (that.data.phone == "") {
      that.toast("手机号码不能为空")
      return false
    } else if (!(/^1[34578]\d{9}$/.test(that.data.phone))) {
      that.toast("请输入正确的手机号码")
      return false;
    } else{
      ajax.wxRequest({
        url: '/index.php/Api/SApi/index/m/getSmsCode',
        data: {
          phone: that.data.phone
        }
      }).then(res => {
        console.log(res)
        if(res.status == 1) {
          that.toast("验证码已发送")
        } else {
          that.toast('验证码发送失败，请稍后重试')
        }
      })
      // FIXME: 倒计时不生效
      let star = 60
      setInterval(function(){
        star = star - 1
        if (star<0){
          star=0
          return false
        }
        that.setData({
          code_time: star
        })
      },1000)
    }
  },

  toast(txt) {
    wx.showToast({
      title: txt,
      icon: "none",
      duration: 1600
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
})
